package com.example.userservice.novel.service;

import com.example.userservice.novel.entity.GenerationHistoryEntity;
import com.example.userservice.novel.entity.NovelStructure;
import com.example.userservice.novel.entity.NovelStructureEntity;
import com.example.userservice.novel.repository.CharacterRepository;
import com.example.userservice.novel.repository.GenerationHistoryRepository;
import com.example.userservice.novel.repository.NovelStructureRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class NovelStorageService {

    @Autowired
    private NovelStructureRepository novelStructureRepository;

    @Autowired
    private CharacterRepository characterRepository;

    @Autowired
    private GenerationHistoryRepository historyRepository;

    /**
     * 保存小说架构
     */
    public NovelStructure saveNovelStructure(NovelStructure novelStructure) {
        try {
            NovelStructureEntity entity = novelStructure.toEntity();
            NovelStructureEntity savedEntity = novelStructureRepository.save(entity);
//            log.info("保存小说架构成功: {} (ID: {})", savedEntity.getNovelName(), savedEntity.getId());
            System.out.println("保存小说架构成功");

            return savedEntity.toDTO();

        } catch (Exception e) {
//            log.error("保存小说架构失败: {}", novelStructure.getNovelName(), e);
            System.out.println("保存小说架构失败");
            throw new RuntimeException("保存失败: " + e.getMessage(), e);
        }
    }

    /**
     * 根据ID查找小说架构
     */
    public NovelStructure findById(Long id) {
        Optional<NovelStructureEntity> entity = novelStructureRepository.findById(id);
        if (entity.isPresent()) {
            return entity.get().toDTO();
        }
        throw new RuntimeException("未找到小说架构，ID: " + id);
    }

    /**
     * 查找所有小说架构
     */
    public List<NovelStructure> findAll() {
        return novelStructureRepository.findByStatus("ACTIVE").stream()
                .map(NovelStructureEntity::toDTO)
                .collect(Collectors.toList());
    }

    /**
     * 根据名称搜索小说
     */
    public List<NovelStructure> searchByNovelName(String novelName) {
        return novelStructureRepository.findByNovelNameContainingIgnoreCase(novelName).stream()
                .map(NovelStructureEntity::toDTO)
                .collect(Collectors.toList());
    }

    /**
     * 获取最近生成的小说
     */
    public List<NovelStructure> findRecentNovels() {
        return novelStructureRepository.findTop10ByOrderByCreatedAtDesc().stream()
                .map(NovelStructureEntity::toDTO)
                .collect(Collectors.toList());
    }

    /**
     * 删除小说架构（软删除）
     */
    public void deleteNovelStructure(Long id) {
        Optional<NovelStructureEntity> entity = novelStructureRepository.findById(id);
        if (entity.isPresent()) {
            NovelStructureEntity novel = entity.get();
            novel.setStatus("DELETED");
            novelStructureRepository.save(novel);
//            log.info("软删除小说架构: {} (ID: {})", novel.getNovelName(), id);
            System.out.println("软删除小说架构");
        }
    }

    /**
     * 保存生成历史记录
     */
    public void saveGenerationHistory(GenerationHistoryEntity history) {
        historyRepository.save(history);
    }

    /**
     * 获取生成统计信息
     */
//    public GenerationStats getGenerationStats() {
//        Long totalCount = historyRepository.count();
//        Long successCount = historyRepository.countBySuccess(true);
//        Long errorCount = historyRepository.countBySuccess(false);
//
//        return GenerationStats.builder()
//                .totalCount(totalCount)
//                .successCount(successCount)
//                .errorCount(errorCount)
//                .successRate(totalCount > 0 ? (double) successCount / totalCount : 0.0)
//                .build();
//    }
}
